package com.ibeetl.admin.core.util;

import com.ibeetl.admin.core.rbac.tree.CatalogItem;
import com.ibeetl.cms.entity.CmsCatalog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CatalogBuildUtil {
    private CatalogBuildUtil() {

    }

    public static CatalogItem buildCatalogTree(List<CmsCatalog> list) {
        CmsCatalog root = new CmsCatalog();
        root.setId(0L);
        root.setType("");
        root.setName("主菜单");
        CatalogItem rootCatalog = new CatalogItem(root);
        buildTreeNode(rootCatalog, list);
        return rootCatalog;
    }
    public static CatalogItem buildCatalogTableTree(List<CmsCatalog> list) {
    	CmsCatalog root = new CmsCatalog();
    	root.setId(0L);
    	root.setType("");
    	root.setName("主菜单");
    	CatalogItem rootCatalog = new CatalogItem(root);
    	buildTableTreeNode(rootCatalog, list);
    	return rootCatalog;
    }

    private static void buildTreeNode(CatalogItem parent, List<CmsCatalog> list) {
        if (parent == null) {
        	return ;
        }

        long id = parent.getId();
        List<CmsCatalog> dels = new ArrayList<>();
        for (CmsCatalog sysCatalog : list) {
            if (sysCatalog.getParentCatalogId() == id) {
                CatalogItem item = new CatalogItem(sysCatalog);
                item.setParent(parent);
                dels.add(sysCatalog);
            }
        }
        list.removeAll(dels);

        if (list.isEmpty()) {
            return;
        }
        
        sortCatalog(parent.getChildren());
        
        for (CatalogItem child : parent.getChildren()) {
            buildTreeNode(child, list);
        }
    }
    
    //不使用CatalogItem里面的children存放子栏目，直接循环取出所有的栏目，用pid识别父栏目，用于treeGrid需要的json格式
    private static List<CatalogItem> buildTableTreeNode(CatalogItem parent, List<CmsCatalog> list) {
    	
    	if (parent != null && parent.getData() != null && (parent.getData().getType() != null && parent.getData().getType().equals(CmsCatalog.TYPE_CATALOGITEM) || parent.getData().getType() == null)) {
            return null;
        }
    	List<CatalogItem> catalogItemList = new ArrayList<CatalogItem>();
    	long id = parent.getId();
    	for (CmsCatalog sysCatalog : list) {
			CatalogItem item = new CatalogItem(sysCatalog);
			item.setParent(parent);
			catalogItemList.add(item);
    	}
    	
    	return catalogItemList;
    }

	private static void sortCatalog(List<CatalogItem> children) {
		Collections.sort(children, new Comparator<CatalogItem>() {

			@Override
			public int compare(CatalogItem o1, CatalogItem o2) {
				return o1.getSeq().compareTo(o2.getSeq());
			}
			
		});
		
	}

}
